<template>
  <el-card class="login-register">
    <h2>{{ isLogin ? '登录' : '注册' }}</h2>
    <el-form :model="form" label-width="80px" @submit.prevent>
      <el-form-item label="用户名">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item v-if="!isLogin" label="邮箱">
        <el-input v-model="form.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="isLogin ? handleLogin() : handleRegister()">
          {{ isLogin ? '登录' : '注册' }}
        </el-button>
        <el-button @click="isLogin = !isLogin" type="text">
          {{ isLogin ? '没有账号？注册' : '已有账号？登录' }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-alert v-if="msg" :title="msg" type="info" show-icon class="msg-alert" />
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const isLogin = ref(true)
const form = ref({ username: '', email: '', password: '' })
const msg = ref('')

const handleLogin = async () => {
  try {
    const res = await axios.post('/user/login', {
      username: form.value.username,
      password: form.value.password
    })
    msg.value = '登录成功！' + JSON.stringify(res.data)
    ElMessage.success('登录成功！')
    // 登录成功后可跳转或存储用户信息
  } catch (e) {
    msg.value = e.response?.data?.detail || '登录失败'
    ElMessage.error(msg.value)
  }
}
const handleRegister = async () => {
  try {
    const res = await axios.post('/user/register', {
      username: form.value.username,
      email: form.value.email,
      password: form.value.password
    })
    msg.value = '注册成功！' + JSON.stringify(res.data)
    isLogin.value = true
    ElMessage.success('注册成功！')
  } catch (e) {
    msg.value = e.response?.data?.detail || '注册失败'
    ElMessage.error(msg.value)
  }
}
</script>

<style scoped>
.login-register {
  max-width: 400px;
  margin: 40px auto;
  padding: 32px 24px;
  border-radius: 12px;
  background: #f8f9fa;
}
.msg-alert {
  margin-top: 16px;
}
</style> 